"""
五子棋游戏主程序
整合棋盘、MCTS算法和GUI界面
"""

import pygame
import sys
from board import Board
from mcts import MCTS
from game_gui import GameGUI
from config import DIFFICULTY, PLAYER_HUMAN, PLAYER_AI


class GomokuGame:
    """五子棋游戏主类"""
    
    def __init__(self, difficulty='medium'):
        """
        初始化游戏
        
        Args:
            difficulty: 难度等级（'easy', 'medium', 'hard', 'expert'）
        """
        self.board = Board()
        self.mcts = MCTS(simulations=DIFFICULTY[difficulty])
        self.gui = GameGUI(self.board)
        
        self.current_player = PLAYER_HUMAN  # 黑方（人类）先手
        self.difficulty = difficulty
        
        print(f"[游戏] 初始化完成，难度: {difficulty}")
        print(f"[游戏] MCTS模拟次数: {DIFFICULTY[difficulty]}")
    
    def run(self):
        """运行游戏主循环"""
        clock = pygame.time.Clock()
        
        while True:
            # 处理事件
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.quit_game()
                
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        self.quit_game()
                    elif event.key == pygame.K_r:
                        self.restart_game()
                
                # 人类玩家落子
                if event.type == pygame.MOUSEBUTTONDOWN and not self.gui.game_over:
                    if self.current_player == PLAYER_HUMAN:
                        self.handle_human_move(event.pos)
            
            # AI玩家落子
            if self.current_player == PLAYER_AI and not self.gui.game_over:
                self.handle_ai_move()
            
            # 绘制界面
            self.gui.draw(self.current_player)
            
            clock.tick(60)  # 60 FPS
    
    def handle_human_move(self, pos):
        """
        处理人类玩家落子
        
        Args:
            pos: 鼠标点击位置
        """
        row, col = self.gui.get_board_position(pos)
        
        print(f"[人类] 尝试落子: ({row}, {col})")
        
        # 尝试落子
        if self.board.make_move(row, col, self.current_player):
            print(f"[人类] 落子成功: ({row}, {col})")
            
            # 检查游戏是否结束
            if self.check_game_over():
                return
            
            # 切换到AI
            self.current_player = PLAYER_AI
        else:
            print(f"[人类] 落子失败: 位置已被占用")
    
    def handle_ai_move(self):
        """处理AI玩家落子"""
        print("[AI] 开始思考...")
        self.gui.set_thinking(True)
        self.gui.draw(self.current_player)
        pygame.display.flip()
        
        # MCTS搜索最佳落子
        move = self.mcts.search(self.board.board, self.current_player)
        
        # 落子
        if move and self.board.make_move(move[0], move[1], self.current_player):
            print(f"[AI] 落子: {move}")
            
            self.gui.set_thinking(False)
            
            # 检查游戏是否结束
            if self.check_game_over():
                return
            
            # 切换到人类
            self.current_player = PLAYER_HUMAN
        else:
            print("[AI] 落子失败！")
            self.gui.set_thinking(False)
    
    def check_game_over(self):
        """
        检查游戏是否结束
        
        Returns:
            bool: 游戏是否结束
        """
        # 检查是否有玩家获胜
        winner = self.board.check_winner()
        
        if winner != 0:
            print(f"[游戏] 游戏结束！获胜者: {'黑方（人类）' if winner == 1 else '白方（AI）'}")
            self.gui.set_game_over(winner)
            return True
        
        # 检查是否平局
        if self.board.is_full():
            print("[游戏] 游戏结束！平局")
            self.gui.set_game_over(0)
            return True
        
        return False
    
    def restart_game(self):
        """重新开始游戏"""
        print("[游戏] 重新开始")
        self.board.reset()
        self.gui.reset()
        self.current_player = PLAYER_HUMAN
    
    def quit_game(self):
        """退出游戏"""
        print("[游戏] 退出")
        pygame.quit()
        sys.exit()


def show_difficulty_menu():
    """
    显示难度选择菜单
    
    Returns:
        str: 选择的难度等级
    """
    print("\n" + "="*50)
    print("五子棋 - MCTS AI对战")
    print("="*50)
    print("\n请选择难度等级：")
    print("1. 简单 (100次模拟，约1秒/步)")
    print("2. 中等 (500次模拟，约3秒/步) [推荐]")
    print("3. 困难 (1000次模拟，约5秒/步)")
    print("4. 专家 (5000次模拟，约20秒/步)")
    print("\n游戏规则：")
    print("- 黑方（人类）先手")
    print("- 点击棋盘落子")
    print("- 先连成5子者获胜")
    print("- 按 R 键重新开始")
    print("- 按 ESC 键退出游戏")
    print("="*50)
    
    difficulty_map = {
        '1': 'easy',
        '2': 'medium',
        '3': 'hard',
        '4': 'expert'
    }
    
    while True:
        choice = input("\n请输入选项 (1-4，默认2): ").strip()
        
        if not choice:
            choice = '2'
        
        if choice in difficulty_map:
            difficulty = difficulty_map[choice]
            print(f"\n已选择难度: {difficulty}")
            print("游戏即将开始...\n")
            return difficulty
        else:
            print("无效选项，请重新输入！")


def main():
    """主函数"""
    try:
        # 显示难度选择菜单
        difficulty = show_difficulty_menu()
        
        # 创建并运行游戏
        game = GomokuGame(difficulty=difficulty)
        game.run()
        
    except KeyboardInterrupt:
        print("\n[游戏] 用户中断")
        pygame.quit()
        sys.exit()
    except Exception as e:
        print(f"\n[错误] {e}")
        import traceback
        traceback.print_exc()
        pygame.quit()
        sys.exit(1)


if __name__ == '__main__':
    main()
